/**
 * 
 */
package mx.fragments;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutionException;

import mx.beans.Game;
import mx.content.Content;
import mx.mxgamer.R;
import mx.util.DomGameConstructor;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * @author v1ctor
 * 
 */
public class GameListFragment extends ListFragment {

	public GameListFragment(){}
	
	SelectedGameListener callBack;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
				android.R.layout.simple_list_item_activated_1 :
					android.R.layout.simple_list_item_1;
		//Log.i("ANDROID VERSION","["+ Build.VERSION.SDK_INT +"]");
		
		DomGameConstructor parser = new DomGameConstructor();
		List<Game> games = null;
		
		try {
			parser.execute(new URL("http://mxcodex.com/games.xml"));
			games = parser.get();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String[] names = new String[games.size()];
		for(int i = 0; i < names.length; i++) {
			names[i] = games.get(i).getName();
		}
		
		// Podría ser otro adaptador que incluya los iconos
//		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), layout, Content.GameList);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), layout, names);
		setListAdapter(adapter);
		
	}// on create

	@Override
	public void onStart() {
		
		super.onStart();
		
        // Cuando estamos en una vista con dos paneles, seleccionamos un elemento. Se hace en onstart, porque aquí ya esta lista la lista
        if (getFragmentManager().findFragmentById(R.id.detallejuegos_fragment) != null) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
	}//onStart
	
	@Override
	public void onAttach(Activity activity) {
		
		super.onAttach(activity);
		
		// La actividad debe de implementar la interfaz
		try{
			callBack = (SelectedGameListener) activity;
		}catch (ClassCastException e){
			Log.e("ON ATTACH", "La clase no implementa SelectedGameListener");
		}
	}// on Attach
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
	
		super.onListItemClick(l, v, position, id);
		
		callBack.onGameSelectedListener(position);
		getListView().setItemChecked(position, true);
		
	}// onListItemClick
}
